package com.zhouyer.study.service.impl;

import com.google.code.kaptcha.Producer;
import com.zhouyer.study.dao.AuthCodeDao;
import com.zhouyer.study.entity.AuthCode;
import com.zhouyer.study.service.CodeService;
import com.zhouyer.study.service.feign.EmailFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * 验证码服务实现逻辑
 *
 * @author zhouyao
 * @version 1.0
 */
@Service
@Slf4j
public class CodeServiceImpl implements CodeService {
    // 验证码有效时间为10分钟
    @Value("${auth-code.expire.time}")
    private long expireTime;

    @Autowired
    private Producer producer;

    @Autowired
    private AuthCodeDao authCodeDao;

    @Autowired
    private EmailFeignClient emailFeignClient;

    @Override
    public boolean createCode(String email) {
        String codeText = producer.createText();
        AuthCode autoCode = new AuthCode();
        autoCode.setCode(codeText);
        autoCode.setEmail(email);
        Date create = new Date();
        autoCode.setCreatetime(create);
        autoCode.setExpiretime(new Date(create.getTime() + expireTime));
        try {
            authCodeDao.save(autoCode);
        } catch (Exception e) {
            log.error("保存code失败",e);
            return false;
        }
        log.info("============验证码微服务调用成功,验证码为" + codeText);
        // 调用email服务feign本地接口
        boolean b = emailFeignClient.sendEmail(email, codeText);
        if (!b) {
            log.info("验证码发送失败");
            return false;
        }
        log.info("验证码发送成功");
        return true;
    }

    @Override
    public int validateCode(String email, String code) {
        AuthCode lastAutoCode = authCodeDao.findLastAutoCode(email);
        if (null == lastAutoCode || !Objects.equals(lastAutoCode.getCode(), code)) {
            // 验证码错误
            return 1;
        }
        if (lastAutoCode.getExpiretime().before(new Date())) {
            // 验证码超时
            return 2;
        }
        // 验证码正确
        return 0;
    }
}
